package app.fichajes.utils;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarUtils {

		
	private static final int YEAR = 0;
	private static final int MONTH = 1;
	private static final int DAY = 2;
	private static final int HOUR = 3;
	private static final int MINUTE = 4;
	private static final int SECOND = 5;
	
	
	public static Calendar getCalendarOfString(String stringDate){
		//Suponemos que el formato de las fechas simepre nos llega de la siguiente forma yyyy-MM-ddTHH:mm:ss
		
		Calendar calendar=null;
		String[] dateAndHour = stringDate.split("T");
		String[] date = dateAndHour[0].split("-");
		String[] hour = dateAndHour[1].split(":");
		calendar = new GregorianCalendar(getIntFromStringParser(YEAR, date[0]),getIntFromStringParser(MONTH, date[1]),getIntFromStringParser(DAY, date[2]), getIntFromStringParser(HOUR, hour[0]), getIntFromStringParser(MINUTE, hour[1]), getIntFromStringParser(SECOND, hour[2]));
		return calendar;
	}
	
	private static int getIntFromStringParser(int typeParser, String stringToParser){
		String stringAnyCero = "";
		boolean characterNoCeroFound = false;
		for (int i = 0; i < stringToParser.length(); i++) {
			Character character = stringToParser.charAt(i);
			if(!character.equals("0") || (character.equals("0") && characterNoCeroFound)){
				stringAnyCero = stringAnyCero + character;
				characterNoCeroFound = true;
			}
		}
		int result =Integer.parseInt(stringAnyCero); 
		if(typeParser==MONTH){
			result--;
		}
		return result;
	}
	
	public static Calendar convertCalendarHourToPhone(Calendar calendarHourToParser, Calendar calendarPhone,Long gmtCountry){
		//Convertimos la hora en los milisegundos a añadir
		Calendar calendarCorrect = new GregorianCalendar();
		calendarCorrect.setTimeInMillis(calendarHourToParser.getTimeInMillis());
		
		int milisecondsToAdd = gmtCountry.intValue() * 3600000;
		if (gmtCountry.compareTo(new Long(0))>0) {
			milisecondsToAdd = -milisecondsToAdd;
		}
		//Situamos la hora del premio en el Gmt
		
		calendarCorrect.add(Calendar.MILLISECOND, milisecondsToAdd);
		//Posteriormente le añadimos la diferencia en milisegundos del teléfono. No nos preocupamos del signo ya que el propio offset del calendar lo lleva
		/*int offSet = calendarHourToParser.get(Calendar.ZONE_OFFSET);
		int offSet2 = calendarHourToParser.get(Calendar.DST_OFFSET);
		//http://developer.android.com/intl/zh-CN/reference/java/util/Date.html -->
		int dst2 = calendarHourToParser.get(Calendar.ZONE_OFFSET) + calendarHourToParser.get(Calendar.DST_OFFSET);
		int dst3 = calendarHourToParser.getTimeZone().getRawOffset();
		*/
		calendarCorrect.add(Calendar.MILLISECOND, calendarHourToParser.get(Calendar.ZONE_OFFSET)+calendarHourToParser.get(Calendar.DST_OFFSET));
		return calendarCorrect;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
